# coding: utf-8

from sqlalchemy import select, text, or_, and_

from bluesky.util import biz
from extentions import db


# {
#   "id": "api",
#   "items": [
#     {
#       "status": 0,
#       "is_delete": 0
#     },
#     {
#       "type": "api",
#       "id": "api"
#     }
#   ],
#   "item_relate_type": "or",  # 控制items之间的关联
#   "relate_type": "or",  # 控制同等级的关联
#   "page_num": 1,
#   "page_size": 10,
#   "order_by": "id desc"
# }
def select_list(session, rtype, param):
    Clz = get_clz(rtype)
    query = session.query(Clz)
    query = biz.process_query(query, param)

    result = query.all()
    return result


def select_count(rtype, param):
    Clz = get_clz(rtype)
    with db.with_session() as session:
        query = session.query(Clz)
        query = biz.process_count_query(query, param)

        result = query.count()
    return result


def one(session, rtype, rid):
    Clz = get_clz(rtype)
    query = session.query(Clz)
    query = query.filter(Clz.id == rid).filter(Clz.is_delete == 0)
    result = query.first()
    return result


def one_by_sql(session, rtype, sql):
    Clz = get_clz(rtype)
    text_sql = text(sql)
    orm_sql = select(Clz).from_statement(text_sql)
    result = session.execute(orm_sql).scalar()
    return result


def list_by_sql(session, rtype, sql):
    Clz = get_clz(rtype)
    text_sql = text(sql)
    orm_sql = select(Clz).from_statement(text_sql)
    result = session.execute(orm_sql).scalars()
    return result.all()


def count_by_sql(rtype, sql):
    eng = db.engine()
    with eng.connect() as conn:
        ret = conn.execute(text(sql))
        for row in ret:
            return row[0]
    return 0


def get_clz(rtype):
    return biz.judge_clz(rtype)


def update_with_session(resource, session):
    Clz = biz.judge_clz(resource.type)
    session.query(Clz).filter(Clz.id == resource.id).update({
        Clz.name: resource.name,
        Clz.parent_id: resource.parent_id,
        Clz.type: resource.type,
        Clz.ext: resource.ext,
        Clz.is_delete: resource.is_delete,
        Clz.status: resource.status,
        Clz.creator: resource.creator,
        Clz.creator_nickname: resource.creator_nickname,
        Clz.created_time: resource.created_time,
        Clz.updated_time: resource.updated_time,
        Clz.deleted_time: resource.deleted_time,
    })
